<template>
	<picker-view class="picker-view" :value="state.value" @change="timeChange">
		<picker-view-column>
			<view class="item" v-for="(item,index) in state.years" :key="index">
				<text class="disabled" v-if="item.disabled">占用</text>
				{{item.value}}年
			</view>
		</picker-view-column>
		<picker-view-column>
			<view class="item" v-for="(item,index) in state.months" :key="index">
				<text class="disabled" v-if="item.disabled">占用</text>
				{{item.value}}月
			</view>
		</picker-view-column>
		<picker-view-column>
			<view class="item" v-for="(item,index) in state.days" :key="index">
				<text class="disabled" v-if="item.disabled">占用</text>
				{{item.value}}日
			</view>
		</picker-view-column>
		<picker-view-column>
			<view class="item" v-for="(item,index) in state.hours" :key="index">
				<text class="disabled" v-if="item.disabled">占用</text>
				{{item.value}}时
			</view>
		</picker-view-column>
		<picker-view-column>
			<view class="item" v-for="(item,index) in state.minutes" :key="index">
				<text class="disabled" v-if="item.disabled">占用</text>
				{{item.value}}分
			</view>
		</picker-view-column>
	</picker-view>
</template>

<script setup>
import { nextTick, onMounted, reactive, watch } from 'vue';
import dayjs from 'dayjs';
const props = defineProps({
	// 不可用的时间
	invalidTime: {
		type: Array,
		default: () => [] // [[start,end],[start,end]]
	},
	modelValue: {
		type: String,
		default: ''
	}
})
const emits = defineEmits(['update:modelValue'])
	const state = reactive({
		oldValue: [],
		value: [],
		currentTime: {},
		years: [],
		months: [],
		days: [],
		hours: [],
		minutes: []
	})
	const getArr = (n,start = 1) => {
		let arr = []
		for(let i = start; i < n + start; i++) {
			arr.push({
				disabled:false,
				value: i
			})
		}
		return arr
	}
	const emitsValue = () => {
		const [yearIndex, monthIndex, dayIndex, hourIndex, minuteIndex] = state.value;
		const {years, months, days, hours, minutes} = state;
		const timeStr = `${years[yearIndex].value}/${months[monthIndex].value}/${days[dayIndex].value} ${hours[hourIndex].value}:${minutes[minuteIndex].value}`
		emits('update:modelValue', timeStr)
	}
	const timeChange = (e) => {
		console.log(e.detail.value,'eeee')
		const [yearNew, monthNew, dayNew, hourNew, minuteNew] = e.detail.value;
		const [yearOld, monthOld, dayOld, hourOld, minuteOld] = state.value
		const yearOldLabel = state.years[yearOld].value,
			  yearNewLabel = state.years[yearNew].value,
			  monthOldLabel = state.months[monthOld].value, 
			  monthNewLabel = state.months[monthNew].value;
		const { currentYear, currentDay, currentMonth } = state.currentTime;
		state.value = e.detail.value;
		if(yearOldLabel !== yearNewLabel || monthOldLabel !== monthNewLabel) {
			// 重新获取当前月份的天数
			const timeStr = `${yearNewLabel}/${monthNewLabel}/01 00:00:01`
			const currentValueMonthDays = dayjs(timeStr).daysInMonth()
			state.days = getArr(currentValueMonthDays)
			if(!state.days[dayNew]) {
				// 修正月份内天数不一致造成的展示错误
				state.value = [yearNew, monthNew, state.days.length - 1, hourNew, minuteNew]
				return;
			}
		}
		nextTick(() => {
			emitsValue()
		})
	}
	const getCurrentTime = (current=null) => {
		const currentTime = current ? new Date(current) : new Date();
		return {
			currentYear: currentTime.getFullYear(), // 年份
			currentMonth: currentTime.getMonth(), // 月份
			currentDay: currentTime.getDate(), // 日期
			currentHour: currentTime.getHours(), // 小时
			currentMinute: currentTime.getMinutes(), // 分钟
			currentMonthDays: dayjs(currentTime).daysInMonth() // 当前月天数
		}
	}
	const setValue = () => {
		state.oldValue = state.value;
		if(props.modelValue) {
			const currentValue = new Date(props.modelValue)
			const { currentYear, currentMonth, currentDay, currentHour, currentMinute, currentMonthDays } = getCurrentTime(currentValue);
			state.days = getArr(currentMonthDays)
			nextTick(() => {
				state.value = [Math.max(0, state.years.findIndex(item => item.value === currentYear)), currentMonth, currentDay - 1, currentHour - 1, currentMinute - 1]
				setColInvalid()
			})
		}else {
			const { currentYear, currentMonth, currentDay, currentHour, currentMinute, currentMonthDays } = state.currentTime;
			state.days = getArr(currentMonthDays)
			nextTick(() => {
				state.value = [Math.max(0, state.years.findIndex(item => item.value === currentYear)), currentMonth, currentDay - 1, currentHour - 1, currentMinute - 1]
				setColInvalid()
			})
		}
	}
	// 设置列的不可用状态
	const setColInvalid = () => {
		if(props.invalidTime.every(item => !item.length)) return;
		if(!state.value.length) return;
		const [yearValue, monthValue, dayValue, hourValue, minuteValue] = state.value;
		const [oldYearValue, oldMonthValue, oldDayValue, oldHourValue, oldMinuteValue] = state.oldValue;
		const yearLabel = state.years[yearValue]?.value, 
			  monthLabel = state.months[monthValue]?.value, 
			  dayLabel = state.days[dayValue]?.value, 
			  hourLabel = state.hours[hourValue]?.value,
			  minuteLabel = state.minutes[minuteValue]?.value;
			  const invalidTimestamp = props.invalidTime.map(item => {
				  return item.map(it => {
					  return {
						  timestamp: dayjs(it).valueOf(),
						  time: getCurrentTime(it),
						  str: it
						}
				  })
			  })
			  if(yearValue !== oldYearValue) {
				  // 控制年份上的 占用状态显示
				  state.years = state.years.map((item,index) => {
					  return {
						  ...item,
						  disabled: invalidTimestamp.some(it => item.value > it[0].time.currentYear && item.value < it[1].time.currentYear)
					  }
				  })
			  }
			  if(yearValue !== oldYearValue || monthValue !== oldMonthValue) {
				  // 控制月份上的 占用状态展示
				  state.months = state.months.map((item,index) => {
					  const monthStart = dayjs(`${yearLabel}/${item.value}/01 00:00:00`).valueOf();
					  const monthDays = dayjs(monthStart).daysInMonth()
					  const monthEnd = dayjs(`${yearLabel}/${item.value}/${monthDays} 00:00:00`).valueOf();
					  return {
						  ...item,
						  disabled: invalidTimestamp.some(it => monthStart > it[0].timestamp && monthEnd < it[1].timestamp)
					  }
				  })
			  }
			  if(yearValue !== oldYearValue || monthValue !== oldMonthValue || dayValue !== oldDayValue) {
				  // 控制日期上的 占用状态展示
				  state.days = state.days.map((item,index) => {
					  const dayStart = dayjs(`${yearLabel}/${monthLabel}/${item.value} 00:00:00`).valueOf();
					  const dayEnd = dayjs(`${yearLabel}/${monthLabel}/${item.value} 23:59:59`).valueOf();
					  return {
						  ...item,
						  disabled: invalidTimestamp.some(it => dayStart > it[0].timestamp && dayEnd < it[1].timestamp)
					  }
				  })
			  }
			  if(yearValue !== oldYearValue || monthValue !== oldMonthValue || dayValue !== oldDayValue || hourValue !== oldHourValue) {
				  // 控制小时上的 占用状态展示
				  state.hours = state.hours.map((item,index) => {
					  const hourStart = dayjs(`${yearLabel}/${monthLabel}/${dayLabel} ${item.value}:00:00`).valueOf()
					  const hourEnd = dayjs(`${yearLabel}/${monthLabel}/${dayLabel} ${item.value}:59:59`).valueOf()
					  return {
						  ...item,
						  disabled: invalidTimestamp.some(it => hourStart > it[0].timestamp && hourEnd < it[1].timestamp)
					  }
				  })
			  }
			  // 控制分钟上的 占用状态展示
			  state.minutes = state.minutes.map((item,index) => {
				  const time = dayjs(`${yearLabel}/${monthLabel}/${dayLabel} ${hourLabel}:${item.value}:00`).valueOf()
				  return {
					  ...item,
					  disabled: invalidTimestamp.some(it => time >= it[0].timestamp && time <= it[1].timestamp)
				  }
			  })
	}
	const init = () => {
		state.currentTime = getCurrentTime()
		const { currentYear, currentMonthDays } = state.currentTime;
		state.years = getArr(50, 2023);// 控制起始年份
		state.months = getArr(12)
		state.hours = getArr(23)
		state.minutes = getArr(59)
		// setValue()
	}
	init()
	watch([() => props.invalidTime, () => props.modelValue], ([invalidTimeNew,modelValueNew],[invalidTimeOld,modelValueOld]) => {
		// init()
		setValue()
	},{
		deep: true,
		immediate: true
	})
</script>

<style lang="scss" scoped>
	.picker-view {
		width: 100%;
		height: 450rpx;
		padding: 10rpx 30rpx;
		box-sizing: border-box;
		.item {
			display: flex;
			justify-content: center;
			align-items: center;
			text-align: center;
			position: relative;
			.disabled {
				position: absolute;
				font-size: 16rpx;
				color: #ff0000;
				top: -3rpx;
				left: 0;
				right: 0;
				margin: auto;
				// right: 10rpx;
			}
		}
	}
</style>